{% extends "bbs/profile/profile_base.html" %}

{% block title %}个人信息 - 有容论坛{% endblock %}

{% block styles %}
{{ super() }}
<style>

</style>
{% endblock %}

{% block profilecontent %}
<div class="card">
    <div class="card-body">
        <div class="text-center p-4">
            <img src="" id="userAvatar" class="img-fluid rounded mx-auto w-25 h-25" data-bs-toggle="modal" data-bs-target="#avatarModal" alt="用户头像">
            <div class="mt-2 fs-2 fw-bold" id="userNickname"></div>
        </div>
        
        <div class="mt-2">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">基本信息</h5>
                </div>
                <ul class="list-group">
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">用户名</div>
                            <div class="col-md-9" id="userLoginname"></div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">性别</div>
                            <div class="col-md-9" id="userGender"></div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">真实姓名</div>
                            <div class="col-md-9" id="userRealName"></div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">身份证号</div>
                            <div class="col-md-9" id="userIdCard"></div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">邮箱</div>
                            <div class="col-md-9" id="userEmail"></div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">手机号</div>
                            <div class="col-md-9" id="userPhone"></div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">QQ号</div>
                            <div class="col-md-9" id="userQQ"></div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="row">
                            <div class="col-md-3">个人简介</div>
                            <div class="col-md-9" id="userDescription"></div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
        
        <div class="text-center mt-3">
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editProfileModal">
                <i class="bi bi-pencil-square"></i> 修改资料
            </button>
        </div>
    </div>
</div>

<!-- 头像上传模态窗口 -->
<div class="modal fade" id="avatarModal" tabindex="-1" aria-labelledby="avatarModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="avatarModalLabel">修改头像</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="avatarForm" action="{{ url_for('profile.upload_avatar') }}" method="POST" enctype="multipart/form-data">
                    <input type="hidden" id="csrf_token" name="csrf_token" value="{{ csrf_token }}">
                    <div class="mb-3">
                        <label for="avatarFile" class="form-label">选择新头像</label>
                        <input class="form-control" type="file" id="avatarFile" name="avatar" accept="image/*">
                        <div class="form-text">支持jpg、jpeg、png、gif格式，最大2MB。</div>
                    </div>
                    <div class="text-center mt-3">
                        <button type="submit" class="btn btn-primary">上传头像</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 修改个人资料模态窗口 -->
<div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editProfileModalLabel">修改个人资料</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="profileForm" action="{{ url_for('profile.update_profile') }}" method="POST">
                    <input type="hidden" id="csrf_token" name="csrf_token" value="{{ csrf_token }}">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="nickname" class="form-label">昵称</label>
                            <input type="text" class="form-control" id="nickname" name="nickname" required data-bv-notempty="昵称不能为空" data-bv-stringlength="true" data-bv-stringlength-max="50" data-bv-stringlength-message="昵称长度不能超过50个字符">
                        </div>
                        <div class="col-md-6">
                            <label for="user_sex" class="form-label">性别</label>
                            <select class="form-select" id="user_sex" name="user_sex">
                                <option value="0">未知</option>
                                <option value="1">男</option>
                                <option value="2">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="real_name" class="form-label">真实姓名</label>
                            <input type="text" class="form-control" id="real_name" name="real_name">
                        </div>
                        <div class="col-md-6">
                            <label for="id_card" class="form-label">身份证号</label>
                            <input type="text" class="form-control" id="id_card" name="id_card" data-bv-digits="true" data-bv-digits-message="身份证号必须为数字" data-bv-stringlength="true" data-bv-stringlength-min="15" data-bv-stringlength-max="18" data-bv-stringlength-message="身份证号长度必须为15或18位">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="email" class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="email" name="email" data-bv-emailaddress="true" data-bv-emailaddress-message="请输入有效的邮箱地址">
                        </div>
                        <div class="col-md-6">
                            <label for="phone" class="form-label">手机号</label>
                            <input type="text" class="form-control" id="phone" name="phone" data-bv-regexp="true" data-bv-regexp-regexp="^1[3-9]\d{9}$" data-bv-regexp-message="请输入有效的手机号码">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="qq" class="form-label">QQ号</label>
                        <input type="text" class="form-control" id="qq" name="qq" data-bv-digits="true" data-bv-digits-message="QQ号必须为数字">
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">个人简介</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                    <div class="text-center">
                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script src="/static/js/validator.min.js"></script>
<script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', async function() {
        // 头像上传成功后，更新本地缓存的用户数据
        const userAvatarUrl = {{ data.avatar_url | tojson if data and data.avatar_url else 'null' }};
        if (userAvatarUrl) {
            console.log('头像上传成功，更新用户数据', userAvatarUrl);
            await UserDataCache.updateUserData('userData', {data: {avatar: userAvatarUrl}}); // 更新本地缓存
            document.getElementById('userAvatar').src = userAvatarUrl;
        }

        // 从本地缓存加载用户数据
        const user_Data = await UserDataCache.getUserData();
        if (!user_Data || !user_Data.data) {
            console.error('用户数据不存在');
            return;
        }
        
        // 填充用户基本信息
        fillUserInfo(user_Data.data);
            
        // 填充表单信息
        fillProfileForm(user_Data.data);
        
        // 初始化表单验证
        var profileValidator = new Validator('profileForm', [
            {
                name: 'nickname',
                display: '昵称{{nickname}}不能为空|昵称长度不能超过50个字符',
                rules: 'required|max_length(50)'
            },
            {
                name: 'email',
                display: '请输入有效的邮箱地址',
                rules: 'is_email'
            },
            {
                name: 'phone',
                display: '请输入有效的手机号码',
                regexp_phone: /^1[3-9]\d{9}$/,
                rules: 'regexp_phone'
            },
            {
                name: 'qq',
                display: 'QQ号必须为数字',
                regexp_qq: /^\d+$/,
                rules: 'regexp_qq'
            },
            {
                name: 'id_card',
                display: '身份证号长度必须为15或18位',
                regexp_idcard: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/,
                rules: 'regexp_idcard'
            }
        ], function(obj, evt) {
            if (obj.errors.length > 0) {
                // 验证失败，阻止表单提交
                evt.preventDefault();
                // 显示第一个错误
                show_noti(obj.errors[0].message, "warning");
                return false;
            }
        });
        
        // 头像上传表单验证
        document.getElementById('avatarForm').addEventListener('submit', function(e) {
            const fileInput = document.getElementById('avatarFile');
            if (!fileInput.files || fileInput.files.length === 0) {
                e.preventDefault();
                show_noti("请选择要上传的头像文件", "warning");
                return false;
            }else{
                const file = fileInput.files[0];
                if (!checkFileExtension(file)) {
                    e.preventDefault();
                    show_noti("头像文件格式不支持", "warning");
                    return false;
                }
                if (!checkFileName(file)) {
                    e.preventDefault();
                    show_noti("头像文件名不能包含特殊字符", "warning");
                    return false;
                }
                if (file.size > 2 * 1024 * 1024) {
                    e.preventDefault();
                    show_noti("头像文件大小不能超过2MB", "warning");
                    return false;
                }
            }
        });
    });

    // 检查文件后缀名是否为指定的类型
    function checkFileExtension(file, extensions=['jpg', 'jpeg', 'png', 'gif']) {
        const fileExtension = file.name.split('.').pop().toLowerCase();
        for (let i = 0; i < extensions.length; i++) {
            if (fileExtension === extensions[i]) {
                return true;
            }
        }
        return false;
    }

    // 检查文件名是否包含特殊的危险字符 '/ \ : * ? " < > |' 等危险字符
    function checkFileName(file) {
        const specialChars = ['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
        for (let i = 0; i < specialChars.length; i++) {
            if (file.name.includes(specialChars[i])) {
                return false;
            }
        }
        return true;
    }
    
    // 填充用户基本信息
    function fillUserInfo(userData) {
        // 填充头像
        document.getElementById('userAvatar').src = userData.avatar || '/static/avatar/default.png';
        
        // 填充昵称
        document.getElementById('userNickname').textContent = userData.nickname || '';
        
        // 填充用户名
        document.getElementById('userLoginname').textContent = userData.loginname || '';
        
        // 填充性别（转换为中文）
        const genderMap = {
            0: '未知',
            1: '男',
            2: '女'
        };
        document.getElementById('userGender').textContent = genderMap[userData.user_sex] || '未知';
        
        // 填充真实姓名
        document.getElementById('userRealName').textContent = userData.real_name || '未设置';
        
        // 填充身份证号（部分隐藏）
        if (userData.id_card) {
            const idCard = userData.id_card;
            const maskedIdCard = idCard.length > 8 ? 
                idCard.substring(0, 4) + '****' + idCard.substring(idCard.length - 4) : 
                '未设置';
            document.getElementById('userIdCard').textContent = maskedIdCard;
        } else {
            document.getElementById('userIdCard').textContent = '未设置';
        }
        
        // 填充邮箱
        document.getElementById('userEmail').textContent = userData.email || '未设置';
        
        // 填充手机号
        document.getElementById('userPhone').textContent = userData.phone || '未设置';
        
        // 填充QQ号
        document.getElementById('userQQ').textContent = userData.qq || '未设置';
        
        // 填充个人简介
        document.getElementById('userDescription').textContent = userData.description || '这个人很懒，什么都没有留下...';
    }
    
    // 填充编辑表单
    function fillProfileForm(userData) {
        document.getElementById('nickname').value = userData.nickname || '';
        document.getElementById('user_sex').value = userData.user_sex || '0';
        document.getElementById('real_name').value = userData.real_name || '';
        document.getElementById('id_card').value = userData.id_card || '';
        document.getElementById('email').value = userData.email || '';
        document.getElementById('phone').value = userData.phone || '';
        document.getElementById('qq').value = userData.qq || '';
        document.getElementById('description').value = userData.description || '';
    }

</script>
{% endblock %}